#include <cstdio>
#include <iostream>
#include <cstdlib>
#include <string>
#include <unistd.h>
#include <pthread.h>
#include <mutex>
#include "mutex.hpp"

using namespace MutexModule;

// pthread_mutex_t glock=PTHREAD_MUTEX_INITIALIZER;
int ticket = 1000;

struct ThreadData
{
    std::string name;
    Mutex *lockp;

    ThreadData(std::string name, Mutex &lock) : name(name), lockp(&lock)
    {
    }

    ~ThreadData()
    {
    }
};

// 加锁的粒度尽量要细一些，尽可能不要包含太多的非临界区代码
void *route(void *arg)
{
    ThreadData *td = static_cast<ThreadData *>(arg);
    // while (1)
    // {
    //     //pthread_mutex_lock(td->lockp);
    //     td->lockp->Lock();
    //     if (ticket > 0)
    //     {
    //         usleep(1000);
    //         printf("%s sells ticket:%d\n", td->name.c_str(), ticket);
    //         ticket--;
    //         //pthread_mutex_unlock(td->lockp);
    //         td->lockp->UnLock();
    //     }
    //     else
    //     {
    //         //pthread_mutex_unlock(td->lockp);
    //         td->lockp->UnLock();
    //         break;
    //     }
    //     usleep(321);
    // }

    while (1)
    {
        {
            MutexGuard guard(*td->lockp);//加锁完成，RAII风格的互斥锁实现，在大括号代码块里，就表示临界区代码，互斥锁的锁定和解锁（自动构造和析构），在这个代码块结束时自动完成。
            if (ticket > 0)
            {
                usleep(1000);
                printf("%s sells ticket:%d\n", td->name.c_str(), ticket);
                ticket--;
            }
            else
            {
                break;
            }
        }
        usleep(321);
    }

    return nullptr;
}

int main(void)
{

    // std::mutex mtx;
    // pthread_mutex_t lock;
    Mutex lock;
    // pthread_mutex_init(&lock, NULL);
    pthread_t t1, t2, t3, t4;
    ThreadData *td1 = new ThreadData("thread 1", lock);
    pthread_create(&t1, NULL, route, td1);

    ThreadData *td2 = new ThreadData("thread 2", lock);
    pthread_create(&t2, NULL, route, td2);

    ThreadData *td3 = new ThreadData("thread 3", lock);
    pthread_create(&t3, NULL, route, td3);

    ThreadData *td4 = new ThreadData("thread 4", lock);
    pthread_create(&t4, NULL, route, td4);

    pthread_join(t1, NULL);
    pthread_join(t2, NULL);
    pthread_join(t3, NULL);
    pthread_join(t4, NULL);

    // pthread_mutex_destroy(&lock);
    return 0;
}